<?php

namespace App\Jobs;

use App\Commission;
use App\Merchant;
use App\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class CommissionJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $order_id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($order_id)
    {
        $this->order_id = $order_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $order = Order::with('detail')->find($this->order_id);
        $merchant = Merchant::where('uid', $order->share_uid)->first();
        $money = 0;

        foreach ($order['detail'] as $key => $value) {
            if ($value['type'] == 0) {
                if (ceil($merchant->commission) == 0) {
                    $money += $value['price'] * $value['number'] * ($merchant->rate / 100);
                } else {
                    $money += ($merchant->commission * $value['number']);
                }
            }
        }

        $data = [
            'uid' => $merchant->uid,
            'order_number' => $order->order_number,
            'commission' => $money,
            'order_uid' => $order->uid,
            'status'=>0
        ];
        Commission::create($data);
    }
}
